﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using AutoFacUtils;
using CashFlow.Web.Def;
using CashFlow.Db.DAL;
using CashFlow.Db.Entity;
using CashFlow.Web.Service;
using CashFlow.Web.Common;
using CashFlow.Web.Areas.ShopManage.Models.Order.Result;
using IShopUserService2 = CashFlow.Web.Service.IShopUserService;

namespace CashFlow.Web.Areas.ShopManage.Service.Implement
{
    public class OrderService : MyService<OrderEntity>, IOrderService
    {
        private IUserService GetUserService() { return AutoFacHelper.Get<IUserService>(); }
        private IShopUserService2 GetShopUserService() { return AutoFacHelper.Get<IShopUserService2>(); }

        public IList<OrderDetailInfoModel> QueryByWhere(
            int shopManagerUserId
            , string date
            , string orderNo
            , string buyer
            , string seller
            , int? state)
        {
            using (var db = SqlSugarHelper.GetDb())
            {
                var query = db.Queryable<OrderEntity>()
                              .InnerJoin<UserInfoEntity>((o, b) => o.BuyerUserId == b.Id)
                              .InnerJoin<UserInfoEntity>((o, b, s) => o.SellerUserId == s.Id)
                              .InnerJoin<ShopUserEntity>((o, b, s, su) => o.BuyerUserId == su.UserId)
                              .Where((o, b, s, su) => su.ShopManagerUserId == shopManagerUserId
                                    && o.CreateTime.ToString("yyyy-MM-dd") == date);

                if (!string.IsNullOrEmpty(orderNo))
                {
                    query = query.Where((o, b, s, su) => o.OrderNo.Contains(orderNo));
                }
                if (!string.IsNullOrEmpty(buyer))
                {
                    query = query.Where((o, b, s, su) => b.Name.Contains(buyer));
                }
                if (!string.IsNullOrEmpty(seller))
                {
                    query = query.Where((o, b, s, su) => s.Name.Contains(seller));
                }
                if (state.HasValue)
                {
                    query = query.Where((o, b, s, su) => o.State == state.Value);
                }

                var ls = query.Select((o, b, s, su) => new OrderDetailInfoModel
                {
                    Id = o.Id,
                    OrderNo = o.OrderNo,
                    Name = o.Name,
                    Amount = o.Amount,
                    Buyer = b.Name,
                    Seller = s.Name,
                    State = o.State,
                    CreateTime = o.CreateTime,
                    Visible = o.Visible,
                    PaymentVoucherImagePath = o.PaymentVoucherImagePath,
                    BuyerUserId = o.BuyerUserId,
                    SellerUserId = o.SellerUserId
                }).ToList();

                return ls;
            }
        }

        public bool IsOrderIdValid(int orderId
            , string date
            , int shopManageUserId)
        {
            using (var db = SqlSugarHelper.GetDb())
            {
                var count = db.Queryable<OrderEntity>()
                              .InnerJoin<ShopUserEntity>((o, su) => o.BuyerUserId == su.UserId)
                              .Where((o, su) => o.Id == orderId
                                && o.CreateTime.ToString("yyyy-MM-dd") == date
                                && su.ShopManagerUserId == shopManageUserId)
                             .Count();
                return count > 0;
            }
        }

        public EUpdateOrderResult UpdateOrder(int orderId
            , string date
            , int buyerUserId
            , int sellerUserId
            , decimal amount)
        {
            var result = EUpdateOrderResult.Other;

            using (var db = SqlSugarHelper.GetDb())
            {
                var n = db.Queryable<OrderEntity>()
                          .Where(x => x.Id != orderId
                            && x.CreateTime.ToString("yyyy-MM-dd") == date
                            && x.BuyerUserId == buyerUserId)
                          .Count();
                if (n == 0)
                {
                    var entity = new OrderEntity();
                    entity.Id = orderId;
                    db.Tracking(entity);
                    entity.BuyerUserId = buyerUserId;
                    entity.SellerUserId = sellerUserId;
                    entity.Amount = amount;
                    int n2 = db.Updateable(entity).ExecuteCommand();
                    if (n2 > 0)
                    {
                        result = EUpdateOrderResult.Success;
                    }
                }
                else
                {
                    result = EUpdateOrderResult.RepeatBuyer;
                }
            }

            return result;
        }

        public bool IsExistOrder(
            int shopManagerUserId
            , string date)
        {
            var service = GetShopUserService();
            var userIds = service.QueryShopAllUserIds(shopManagerUserId, null);
            using (var db = SqlSugarHelper.GetDb())
            {
                int n = db.Queryable<OrderEntity>()
                          .Where(x => x.CreateTime.ToString("yyyy-MM-dd") == date
                            && userIds.Contains(x.BuyerUserId))
                          .Count();
                return n > 0;
            }
        }

        public bool ReleaseOrder(
            int shopManagerUserId
            , string date)
        {
            using (var db = SqlSugarHelper.GetDb())
            {
                int n = db.Updateable<OrderEntity>()
                          .InnerJoin<ShopUserEntity>((o, su) => o.BuyerUserId == su.UserId)
                          .InnerJoin<UserInfoEntity>((o, su, u) => su.UserId == u.Id)
                          .Where((o, su, u) => o.CreateTime.ToString("yyyy-MM-dd") == date
                                && su.ShopManagerUserId == shopManagerUserId)
                          .SetColumns((o, su, u) => new OrderEntity { Visible = 1 })
                          .ExecuteCommand();
                return n > 0;
            }
        }

        public ECreateOrderResult CreateOrder(
            int buyerUserId
            , int sellerUserId
            , decimal amount
            , string date)
        {
            var result = ECreateOrderResult.Other;

            using (var db = SqlSugarHelper.GetDb())
            {
                int n = db.Queryable<OrderEntity>()
                          .Where(x => x.BuyerUserId == buyerUserId
                            && x.CreateTime.ToString("yyyy-MM-dd") == date)
                          .Count();
                if (n > 0)
                {
                    result = ECreateOrderResult.RepeatBuyer;
                }
                else
                {
                    var entity = new OrderEntity();
                    entity.BuyerUserId = buyerUserId;
                    entity.SellerUserId = sellerUserId;
                    entity.Amount = amount;
                    entity.Visible = 0;
                    entity.State = 0;
                    entity.OrderNo = MyCommonTool.CreateOrderNo();
                    entity.CreateTime = DateTime.Now;
                    entity.Name = MyCommonTool.GetProductName();
                    entity.PaymentVoucherImagePath = "";

                    int n2 = db.Insertable(entity).ExecuteCommand();
                    if (n2 > 0)
                    {
                        result = ECreateOrderResult.Success;
                    }
                }
            }

            return result;
        }

        public IList<OrderBuyerInfoModel> QueryOrderByDate(
             int shopManagerUserId
            , string date)
        {
            using (var db = SqlSugarHelper.GetDb())
            {
                var ls = db.Queryable<OrderEntity>()
                           .InnerJoin<UserInfoEntity>((o, u) => o.BuyerUserId == u.Id)
                           .InnerJoin<ShopUserEntity>((o, u, su) => o.BuyerUserId == su.UserId)
                           .Where((o, u, su) => su.ShopManagerUserId == shopManagerUserId
                                && o.CreateTime.ToString("yyyy-MM-dd") == date)
                           .OrderBy((o, u, su) => o.Amount)
                           .Select((o, u, su) => new OrderBuyerInfoModel
                           {
                               UserId = u.Id,
                               Name = u.Name,
                               Amount = o.Amount,
                               Phone = u.Phone
                           })
                           .ToList();
                return ls;
            }
        }
    }
}